//扁平化菜单
const flat = function(data, list = [], key = 'children') {
    data.forEach(e => {
        list.push(e)
        if(e[key]) {
            flat(e[key], list, key)
        }
    })
    return list
}
//通过parendId查找父级
const findByParentId = function(data, parentId, list = []) {
    const item = data.find(e => e.id === parentId)
    if(item) {
        list.unshift(item)
        if(item.parentId) findByParentId(data, item.parentId, list)
    }
    return list
}
//通过key查找对应菜单 及 父级菜单
const findByKey = function(data, value, key) {
    const map = flat(data);
    const item = map.find(e => e[key] === value)
    let list = [];
    if(item) {
        list.push(item)
        if(item.parentId) {
            list = findByParentId(map, item.parentId, list)
        }
    }
    return list
}

const menusModule = {
    state: {
        menus: null,//菜单
        authAcl: null,//按钮权限
    },
    mutations: {
        SET_MUENS (state, data) {
            //设置菜单 及 权限信息
            state.menus = data.menus
            state.authAcl = data.acl
            localStorage.setItem('menus', JSON.stringify(data.menus))
            localStorage.setItem('acl', JSON.stringify(data.acl))
        },
        GET_MENU_BY_PATH (state, {path, resolve}) {
            (path && resolve) ? resolve(findByKey(state.menus || [], path, 'path')) : null
        }
    },
    actions: {
        // 用户菜单
        setMenus ({ commit }, data) {
            commit('SET_MUENS', data)
        },
        //通过path获取菜单及其父级
        getMenuByPath ({ commit }, {path, resolve}) {
            commit('GET_MENU_BY_PATH', {path, resolve})
        }
    }
}

export default menusModule